﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Text;
using System.IO;

namespace WebApp.Models
{
    public class StockCollection
    {
        private Dictionary<String, Stock> stocks = new Dictionary<String, Stock>();

        public Dictionary<String, Stock> Stocks
        {
            get { return stocks; }
        }

        public StockCollection(List<String> symbols)
        {
            foreach (String symbol in symbols)
            {
                Stock stock = new Stock(symbol);
                stocks[symbol.ToUpper()] = stock;
            }
        }

        public StockCollection(List<Stock> stocks)
        {
            foreach (Stock stock in stocks)
            {
                this.stocks[stock.Symbol] = stock;
            }
        }

        public void FetchPrices()
        {
            if (stocks.Count == 0)
                return;

            StringBuilder url = new StringBuilder(
                "http://finance.yahoo.com/d/quotes.csv?f=sl1pjkn&s=");
            foreach (KeyValuePair<String, Stock> pair in stocks)
            {
                url.Append(pair.Value.Symbol);
                url.Append("+");
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream());
            String csv = null;
            // TODO replace with a legit CSV parser
            while ((csv = sr.ReadLine()) != null)
            {
                String[] parts = csv.Split(',');
                // Must be at least 6 parts. Name can contain commas!!!!
                if (parts.Length < 6)
                    return;
                int len = parts.Length;
                String symbol = parts[0].Replace("\"", "").ToUpper();

                String name = parts[5].Replace("\"", "");
                if (len > 6)
                {
                    for (int i = 6; i < len; i++)
                        name += "," + parts[i].Replace("\"", "");
                }
                Stock stock = stocks[symbol];
                stock.Name = name;
                stock.CurrentPrice = Double.Parse(parts[1]);
                stock.Closing = Double.Parse(parts[2]);
                stock.FiftyTwoWeekLow = Double.Parse(parts[3]);
                stock.FiftyTwoWeekHigh = Double.Parse(parts[4]);
            }
        }
    }
}